package com.example.orderfood2.RecyclerViewAdapter;

import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.orderfood2.R;

public class StudentAdapter extends RecyclerView.Adapter<StudentAdapter.ViewHolder> {
    // 用于存储要显示的数据列表
    private Cursor cursor;

    private StudentAdapter.OnItemClickListener listener;

    // 构造函数，接收数据列表作为参数
    public StudentAdapter(Cursor cursor) {
        this.cursor = cursor;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder {
        TextView tvId, tvUserName;
        Button btnEdit,btnDelete;

        public ViewHolder(View itemView) {
            super(itemView);
            // 初始化 TextView
            tvId = itemView.findViewById(R.id.tv_student_id);
            tvUserName = itemView.findViewById(R.id.tv_username);
            btnEdit=itemView.findViewById(R.id.btn_student_edit);
            btnDelete=itemView.findViewById(R.id.btn_student_delete);
        }
    }


    @NonNull
    @Override
    public StudentAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_student, parent, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull StudentAdapter.ViewHolder holder, int position) {
        if (cursor.moveToPosition(position)) {
            int id = cursor.getInt(0);
            String username = cursor.getString(1);
            holder.tvId.setText(String.valueOf(id));
            holder.tvUserName.setText(username);
            holder.btnEdit.setOnClickListener(v->{
                if(listener!=null){
                    listener.onEditClick(position,id,username);
                }
            });
            // 删除按钮点击事件
            holder.btnDelete.setOnClickListener(v -> {
                if (listener != null) {
                    listener.onDeleteClick(position, id);
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return cursor.getCount();
    }

    public interface OnItemClickListener{
        void onEditClick(int position, int id, String username);
        void onDeleteClick(int position, int id);
    }

    public void setOnItemClickListener(StudentAdapter.OnItemClickListener listener){this.listener =listener;}
}
